package com.hzit.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.hzit.constant.HzitConstants;
import com.hzit.entity.LoginUser;
import com.hzit.entity.User;
import com.hzit.mapper.UserMapper;
import com.hzit.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzit.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wf
 * @since 2024-03-01
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
	@Autowired
	private StringRedisTemplate redisTemplate;
	@Autowired
	private AuthenticationManager authenticationManager;
	@Override
	public List<String> findPermissionsByUsername(String username) {
		return baseMapper.findPermissionsByUsername(username);
	}

	//1. 用户登录认证
	@Override
	public Map login(UserVo vo) {
		//1.1 构造认证对象
		UsernamePasswordAuthenticationToken authticateToken = new UsernamePasswordAuthenticationToken(vo.getUsername(),vo.getPassword());
		Authentication authenticate = authenticationManager.authenticate(authticateToken);
		if(authenticate == null){
			throw new RuntimeException("认证失败！");
		}
		LoginUser loginUser = (LoginUser) authenticate.getPrincipal();

		//1.2 生成一个token串，并把这个token串放到redis中且同时返回给前端
		//1.2.1 生成一个token串
		String token = UUID.randomUUID().toString().replace("-","");
		//1.2.2 生成一个redis的key
		String key = getKey(token);
		//1.2.3 将登录用户保存到redis中(使用hutool工具序列化和反序列化)
		String s = JSONUtil.toJsonStr(loginUser);
		// redisTemplate.opsForValue().set(key, JSON.toJSONString(loginUser));
		redisTemplate.opsForValue().set(key, s);

		//1.2.4 将token返回给前端
		Map map = new HashMap();
		map.put("token",token);
		return map;
	}

	private String getKey(String token) {
		return HzitConstants.LOGIN_TOKEN_PREFIX + token;
	}


}
